package cn.itcast.hotel.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.itcast.hotel.dto.HotelSearchDto;
import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.IHotelService;
import cn.itcast.hotel.vo.PageResult;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private RestHighLevelClient client;
    /**
     * 搜索酒店数据，分页展示
     * @param searchDto
     * @return
     */
    @Override
    public PageResult getListBySearch(HotelSearchDto searchDto) {
        try {
            System.err.println(searchDto);
            //准备Request
            SearchRequest request = new SearchRequest("hotel");
            //准备DSL
            //查询--boolQuery
            buildBasicQuery(searchDto, request);
            //分页
            Integer page = searchDto.getPage();
            Integer size = searchDto.getSize();
            int from = (page - 1) * size;
            request.source().from(from).size(size);
            //排序--geo_location
            String location = searchDto.getLocation();
            if (StringUtils.isNotBlank(location)) {
                request.source().sort(SortBuilders
                        .geoDistanceSort("location", new GeoPoint(location))
                        .order(SortOrder.ASC)
                        .unit(DistanceUnit.KILOMETERS));
            }
            //排序--price/score/default
            String sortBy = searchDto.getSortBy();
            if (StringUtils.isNotBlank(sortBy)) {
                switch (sortBy) {
                    case "price": {
                        request.source().sort(sortBy, SortOrder.ASC);
                        break;
                    }
                    case "score": {
                        request.source().sort(sortBy, SortOrder.DESC);
                        break;
                    }
                    default:
                        break;
                }
            }
            //发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //处理响应
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException("网络异常，请稍后重试");
        }
    }

    /**
     * 搜索框自动补全
     * @param prefix
     * @return
     */
    @Override
    public List<String> getSuggestions(String prefix) {
        try {
            //准备Request
            SearchRequest request = new SearchRequest("hotel");
            //准备DSL
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "suggestions",
                    SuggestBuilders.completionSuggestion("suggestion")
                    .prefix(prefix)
                    .skipDuplicates(true)
                    .size(10)
                    ));
            //发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //处理响应
            Suggest suggest = response.getSuggest();
            //根据补全查询名称，获取全部结果
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            //获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            //遍历options构造返回值
            List<String> list = new ArrayList<>();
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                System.err.println(text);
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 数据聚合
     * @param searchDto
     * @return
     */
    @Override
    public Map<String, List<String>> getFilters(HotelSearchDto searchDto) {
        try {
            //准备Request
            SearchRequest request = new SearchRequest("hotel");
            //准备DSL
            //query --》限定聚合范围
            buildBasicQuery(searchDto, request);
            //设置size(0)-->清除文档内容，只保留聚合结果
            request.source().size(0);
            //聚合 --> brand、city、star
            buildAggregation(request, "city");
            buildAggregation(request, "starName");
            buildAggregation(request, "brand");
            //处理响应
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Map<String, List<String>> result = new HashMap<>();
            //封装城市集合
            List<String> cityList = getAggByName(response, "cityAgg");
            //封装星级集合
            List<String> starList = getAggByName(response, "starNameAgg");
            //封装品牌集合
            List<String> brandList = getAggByName(response, "brandAgg");
            //构造返回值
            result.put("city", cityList);
            result.put("starName", starList);
            result.put("brand", brandList);
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据聚合名称获取聚合结果
     * @param response  Searchrequest
     * @param aggName   聚合名称
     * @return
     */
    private List<String> getAggByName(SearchResponse response, String aggName) {
        List<String> list = new ArrayList<>();
        Aggregations aggregations = response.getAggregations();
        Terms terms = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            list.add(key);
        }
        return list;
    }

    /**
     * 聚合指定字段
     * @param request   SearchRequest
     * @param field     字段名
     */
    private void buildAggregation(SearchRequest request, String field) {
        request.source().aggregation(AggregationBuilders
                .terms(field + "Agg").field(field).size(100));
    }

    /**
     * 根据id删除
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        try {
            DeleteRequest request = new DeleteRequest("hotel", id.toString());
            client.delete(request, RequestOptions.DEFAULT);
            System.err.println("删除成功。。。");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据id新增/修改
     * @param id
     */
    @Override
    public void insertById(Long id) {
        try {
            Hotel hotel = this.getById(id);
            System.err.println(hotel);
            HotelDoc hotelDoc = new HotelDoc(hotel);
            IndexRequest request = new IndexRequest("hotel").id(id.toString());
            request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
            client.index(request, RequestOptions.DEFAULT);
            System.err.println("添加/修改成功。。。");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 准备DSL-布尔查询
     * @param searchDto
     * @param request
     */
    private void buildBasicQuery(HotelSearchDto searchDto, SearchRequest request) {
        //构造BoolQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //关键字查询--match
        String key = searchDto.getKey();
        if (StringUtils.isNotBlank(key)) {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        } else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        //城市查询--term
        String city = searchDto.getCity();
        if (StringUtils.isNotBlank(city)) {
            boolQuery.must(QueryBuilders.termQuery("city", city));
        }
        //星级查询--term
        String starName = searchDto.getStarName();
        if (StringUtils.isNotBlank(starName)) {
            starName = starName + "级";
            boolQuery.must(QueryBuilders.termQuery("starName", starName));
        }
        //品牌查询--term
        String brand = searchDto.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQuery.must(QueryBuilders.termQuery("brand", brand));
        }
        //价格查询--range
        Integer minPrice = searchDto.getMinPrice();
        Integer maxPrice = searchDto.getMaxPrice();
        if (ObjectUtil.isNotEmpty(minPrice)) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice));
        }
        if (ObjectUtil.isNotEmpty(maxPrice)) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").lte(maxPrice));
        }
        //算分控制
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                // 原始查询，相关性算分的查询
                boolQuery,
                // function score的数组
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        // 其中的一个function score 元素
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                // 过滤条件
                                QueryBuilders.termQuery("isAD", true),
                                // 算分函数
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                }
        );
        //将functionScoreQuery放入source
        request.source().query(functionScoreQuery);
    }

    /**
     * 处理响应
     * @param response
     * @return
     */
    private PageResult handleResponse(SearchResponse response) {
        SearchHits searchHits = response.getHits();
        long total = searchHits.getTotalHits().value;
        if (total == 0) {
            return new PageResult();
        }
        SearchHit[] hits = searchHits.getHits();
        List<HotelDoc> hotelDocs = new ArrayList<>();
        for (SearchHit hit : hits) {
            String hotelDocJson = hit.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(hotelDocJson, HotelDoc.class);
            Object[] sortValues = hit.getSortValues();
            //添加距离
            if (ArrayUtil.isNotEmpty(sortValues)) {
                hotelDoc.setDistance(sortValues[0]);
            }
            hotelDocs.add(hotelDoc);
        }
        System.err.println("搜索到" + total + "条结果。");
        return new PageResult(total, hotelDocs);
    }
}
